<?php

/**
 * API的model
 * author: 爱是西瓜
 * DateTime: 2018/5/01
 */

class ApiModel{

    /**
     * 客户端数据转数据库格式
     * @param $data
     * @param $kf
     * @return array
     */
    public static function dataToDb($data,$kf){
        $log = [
            'user_id'=>$data['uid'],
            'client_id'=>$data['id'],
            'user_name'=>$data['name'],
            'user_avatar'=>$data['avatar'],
            'data'=>$data['data'],
            'user_ip'=>$data['ip'],
            'kf_id'=>$kf['id'],
            'group_id'=>$data['group'],
            'start_time'=> time(),
            'end_time'=>0
        ];
        return $log;
    }

    /**
     * 数据库数据转客户端格式
     * @param $data
     * @return array
     */
    public static function dbToData($data){

        $log = [
            'id'=>$data['user_id'],
            'client_id'=>$data['client_id'],
            'name'=>$data['user_name'],
            'avatar'=>$data['user_avatar'],
            'ip'=>$data['user_ip'],
            'group'=>$data['group_id'],
        ];
        return $log;
    }







    /**
     * 根据用户编号获取当前连接列表
     * @param $user_id
     * @return array
     */
    public static function getUidLinks($user_id){

        //兼容客服id
        if(!is_numeric($user_id) && strpos($user_id,'KF')===0){
            return [self::dbToData(Cache::getUidKf($user_id))];
        }

        //获取当前连接列表
        $link_list = Db::select('ws_service_log',"where end_time=0 and user_id='{$user_id}'");
        return $link_list;
    }


    /**
     * 根据组与用户编号获取在线客服列表
     * @param $group_id
     * @param int $uid
     * @return array
     */
    public static function getkfOnline($group_id,$uid=0){

        $sql = "select *,(
	select count(*) from ws_service_log where kf_id=u.id and end_time=0
) as count,(
    select count(*) from ws_service_log where kf_id=u.id and user_id='{$uid}'
) as uid_num from ws_users as u where group_id='{$group_id}' ORDER BY `online` asc,uid_num desc,count desc";

        $kf_list = Db::fetchAll($sql);
        return $kf_list;
    }


    /**
     * 根据组与用户编号获取在线客服
     * @param $group_id
     * @param int $uid
     * @return mixed
     */
    public static function getkf($group_id,$uid=0){

        //分配客服
        $kf_config = Db::find('ws_kf_config',"where id=1");

        $kf_list = self::getkfOnline($group_id,$uid);
        foreach ($kf_list as $k=>$kf){
            if($kf_config['max_service'] == 0 || $kf['count'] <= $kf_config['max_service']){
                break;
            }
        }
        unset($kf_list);
        return $kf;

    }

    /**
     * 更新当前统计信息
     * @param int $flag
     */
    public static function saveNowData($flag = 1){

        // 上午 8点 到 22 点开始统计
        if (date('H') < 8 || date('H') > 22) {
            return;
        }

        // 当前正在接入的人 和 在线客服数
        $onlineKf   = count(Cache::kfList());
        $nowTalking = self::getNowCliNum();

        //接入的连接数
        $success_in = count(Cache::getCliList());
        $total_in = self::getTodayCliNum();

        // 在队列中的用户
        $inQueue = $success_in-$nowTalking-$onlineKf;
        $inQueue = $inQueue>0?$inQueue:0;

        $param = [
            'is_talking' => $nowTalking,
            'in_queue'   => $inQueue,
            'online_kf'  => $onlineKf,
            'success_in' => $success_in,
            'total_in'   => $total_in,
            'now_date'   => date('Y-m-d')
        ];

        Db::update($param,'ws_now_data','WHERE id=1');

        if (2 == $flag) {
            $param = [
                'is_talking' => $nowTalking,
                'in_queue'   => $inQueue,
                'online_kf'  => $onlineKf,
                'success_in' => $success_in,
                'total_in'   => $total_in,
                'add_date'   => date('Y-m-d'),
                'add_hour'   => date('H'),
                'add_minute' => date('i'),
            ];

            Db::add($param,'ws_service_data');
        }
        unset($nowTalking, $inQueue, $onlineKf, $param);
    }

    /**
     * 获取当前咨询正在咨询的连接数
     * @return int
     */
    public static function getNowCliNum(){
        $row = Db::find('ws_service_log',"WHERE end_time=0","count(1) as num");
        return intval($row['num']);
    }

    /**
     * 获取今日链接数
     * @return int
     */
    public static function getTodayCliNum(){
        $toDay = strtotime(date('Y-m-d'));
        $row = Db::find('ws_service_log',"where start_time >= {$toDay} ","count(1) as num");
        return intval($row['num']);
    }



}
